package com.ruoyi.web.controller.energy;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.energy.service.IEmsDeviceDataStatisticsService;

/**
 * 设备数据统计Controller
 * 基于TDengine实现设备数据统计、趋势分析等功能
 * 
 * @author ruoyi
 * @date 2025-06-30
 */
@RestController
@RequestMapping("/energy/statistics")
public class EmsDeviceDataStatisticsController extends BaseController {
    
    @Autowired
    private IEmsDeviceDataStatisticsService statisticsService;

    /**
     * 获取设备概览统计
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/overview")
    public AjaxResult getOverviewStatistics() {
        try {
            Map<String, Object> overview = statisticsService.getDeviceOverviewStatistics();
            return success(overview);
        } catch (Exception e) {
            return error("获取设备概览统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备能耗统计
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/energy")
    public AjaxResult getEnergyStatistics(@RequestParam(required = false) String deviceCode,
                                         @RequestParam(required = false) String energyType,
                                         @RequestParam(required = false) String startTime,
                                         @RequestParam(required = false) String endTime,
                                         @RequestParam(defaultValue = "hour") String groupBy) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            List<Map<String, Object>> statistics = statisticsService.getDeviceEnergyStatistics(
                deviceCode, energyType, start, end, groupBy);

            return success(statistics);
        } catch (Exception e) {
            return error("获取设备能耗统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备运行状态统计
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/status")
    public AjaxResult getStatusStatistics(@RequestParam(required = false) String deviceCode,
                                         @RequestParam(required = false) String startTime,
                                         @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            Map<String, Object> statistics = statisticsService.getDeviceStatusStatistics(deviceCode, start, end);
            return success(statistics);
        } catch (Exception e) {
            return error("获取设备运行状态统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备效率分析
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/efficiency/{deviceCode}")
    public AjaxResult getEfficiencyAnalysis(@PathVariable String deviceCode,
                                           @RequestParam(required = false) String startTime,
                                           @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近7天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            Map<String, Object> analysis = statisticsService.getDeviceEfficiencyAnalysis(deviceCode, start, end);
            return success(analysis);
        } catch (Exception e) {
            return error("获取设备效率分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备负载趋势
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/load/{deviceCode}")
    public AjaxResult getLoadTrend(@PathVariable String deviceCode,
                                  @RequestParam(required = false) String startTime,
                                  @RequestParam(required = false) String endTime,
                                  @RequestParam(defaultValue = "1h") String interval) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近24小时
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            List<Map<String, Object>> trend = statisticsService.getDeviceLoadTrend(deviceCode, start, end, interval);
            return success(trend);
        } catch (Exception e) {
            return error("获取设备负载趋势失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备告警统计
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/alarm")
    public AjaxResult getAlarmStatistics(@RequestParam(required = false) String deviceCode,
                                        @RequestParam(required = false) String startTime,
                                        @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近7天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            Map<String, Object> statistics = statisticsService.getDeviceAlarmStatistics(deviceCode, start, end);
            return success(statistics);
        } catch (Exception e) {
            return error("获取设备告警统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备对比分析
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/comparison")
    public AjaxResult getComparisonAnalysis(@RequestParam List<String> deviceCodes,
                                           @RequestParam(required = false) String startTime,
                                           @RequestParam(required = false) String endTime,
                                           @RequestParam(required = false) List<String> metrics) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近7天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            List<Map<String, Object>> analysis = statisticsService.getDeviceComparisonAnalysis(
                deviceCodes, start, end, metrics);

            return success(analysis);
        } catch (Exception e) {
            return error("获取设备对比分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备峰谷电分析
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/peakvalley/{deviceCode}")
    public AjaxResult getPeakValleyAnalysis(@PathVariable String deviceCode,
                                           @RequestParam(required = false) String startTime,
                                           @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近30天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 30 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            Map<String, Object> analysis = statisticsService.getDevicePeakValleyAnalysis(deviceCode, start, end);
            return success(analysis);
        } catch (Exception e) {
            return error("获取设备峰谷电分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备数据质量报告
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/quality")
    public AjaxResult getDataQualityReport(@RequestParam(required = false) String deviceCode,
                                          @RequestParam(required = false) String startTime,
                                          @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近7天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    return error("时间参数格式错误");
                }
            }

            Map<String, Object> report = statisticsService.getDeviceDataQualityReport(deviceCode, start, end);
            return success(report);
        } catch (Exception e) {
            return error("获取设备数据质量报告失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备能耗排行榜
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/ranking")
    public AjaxResult getEnergyRanking(@RequestParam(required = false) String energyType,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime,
                                      @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 参数验证
            if (startTime == null || endTime == null) {
                // 如果没有提供时间范围，使用默认的最近7天
                Date end = new Date();
                Date start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000L);

                List<Map<String, Object>> ranking = statisticsService.getDeviceEnergyRanking(
                    energyType != null ? energyType : "ELECTRIC", start, end, limit);

                return success(ranking);
            }

            Date start = DateUtils.parseDate(startTime);
            Date end = DateUtils.parseDate(endTime);

            if (start == null || end == null) {
                return error("时间参数格式错误");
            }

            List<Map<String, Object>> ranking = statisticsService.getDeviceEnergyRanking(
                energyType != null ? energyType : "ELECTRIC", start, end, limit);

            return success(ranking);
        } catch (Exception e) {
            return error("获取设备能耗排行榜失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备实时监控数据
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:view')")
    @GetMapping("/realtime")
    public AjaxResult getRealtimeMonitorData(@RequestParam(required = false) List<String> deviceCodes) {
        try {
            List<Map<String, Object>> data = statisticsService.getDeviceRealtimeMonitorData(deviceCodes);
            return success(data);
        } catch (Exception e) {
            return error("获取设备实时监控数据失败: " + e.getMessage());
        }
    }

    /**
     * 导出设备统计报表
     */
    @PreAuthorize("@ss.hasPermi('energy:statistics:export')")
    @Log(title = "设备统计报表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void exportStatisticsReport(HttpServletResponse response,
                                      @RequestParam String reportType,
                                      @RequestParam(required = false) String deviceCode,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime) {
        try {
            Date start, end;

            // 如果没有提供时间范围，使用默认的最近30天
            if (startTime == null || endTime == null) {
                end = new Date();
                start = new Date(end.getTime() - 30 * 24 * 60 * 60 * 1000L);
            } else {
                start = DateUtils.parseDate(startTime);
                end = DateUtils.parseDate(endTime);

                if (start == null || end == null) {
                    logger.error("导出报表时间参数格式错误: startTime={}, endTime={}", startTime, endTime);
                    return;
                }
            }

            List<Map<String, Object>> data = statisticsService.exportDeviceStatisticsReport(
                reportType, deviceCode, start, end);

            // 转换数据类型以适配ExcelUtil
            @SuppressWarnings("unchecked")
            List<Map> exportData = (List<Map>) (List<?>) data;

            ExcelUtil<Map> util = new ExcelUtil<>(Map.class);
            util.exportExcel(response, exportData, "设备统计报表");
        } catch (Exception e) {
            logger.error("导出设备统计报表失败", e);
        }
    }
}
